<template>
  <div class="draft-list">
    <div class="page-header">
      <h2>草稿箱</h2>
      <el-button type="primary" @click="$router.push('/editor')">新建文章</el-button>
    </div>
    
    <el-table :data="drafts" style="width: 100%">
      <el-table-column prop="title" label="标题" min-width="200">
        <template #default="scope">
          <el-link type="primary" @click="$router.push(`/editor/${scope.row.id}`)">
            {{ scope.row.title }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column prop="updated_at" label="最后修改" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.updated_at) }}
        </template>
      </el-table-column>
      <el-table-column prop="word_count" label="字数" width="100" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button-group>
            <el-button size="small" @click="editArticle(scope.row)">编辑</el-button>
            <el-button size="small" type="success" @click="publishArticle(scope.row)">发布</el-button>
            <el-button size="small" type="danger" @click="deleteArticle(scope.row)">删除</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import { fetchArticles, deleteArticle as deleteArticleApi } from '../api/article'

const router = useRouter()
const drafts = ref([])

const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm')
}

const editArticle = (article) => {
  router.push(`/editor/${article.id}`)
}

const publishArticle = async (article) => {
  // TODO: 实现发布功能
  ElMessage.success('发布成功')
}

const deleteArticle = async (article) => {
  try {
    await ElMessageBox.confirm('确定要删除这篇文章吗？', '警告', {
      type: 'warning'
    })
    await deleteArticleApi(article.id)
    ElMessage.success('删除成功')
    loadDrafts()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const loadDrafts = async () => {
  try {
    // 只获取草稿状态的文章
    const articles = await fetchArticles()
    drafts.value = articles.filter(article => article.status === 'draft')
  } catch (error) {
    ElMessage.error('获取草稿列表失败')
  }
}

onMounted(() => {
  loadDrafts()
})
</script>

<style scoped>
.draft-list {
  padding: 24px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}
</style> 